package org.eclipseuseradmin.internal.ui;

import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IEditorRegistry;
import org.eclipseuseradmin.ui.BaseRoleElementAdapter;
import org.eclipseuseradmin.ui.IGroup;
import org.eclipseuseradmin.ui.IRole;
import org.eclipseuseradmin.ui.IRoleElement;
import org.eclipseuseradmin.ui.IRoleRootDescriptor;
import org.eclipseuseradmin.ui.IUser;

public class RolesLabelProvider extends LabelProvider {

	private IEditorRegistry editorRegistry;

	private IAdapterManager adapterManager;

	public Image getImage(Object element) {

		if (element instanceof IRoleRootDescriptor) {
			return UserAdminUiPlugin.getImageDescriptor("/icons/root_obj.gif")
					.createImage();
		}
		if (adapterManager.getAdapter(element, IUser.class) != null) {
			return UserAdminUiPlugin.getImageDescriptor("/icons/user_obj.gif")
					.createImage();
		}
		if (adapterManager.getAdapter(element, IGroup.class) != null) {
			return UserAdminUiPlugin.getImageDescriptor("/icons/group_obj.gif")
					.createImage();
		}
		if (adapterManager.getAdapter(element, IRole.class) != null) {
			return UserAdminUiPlugin.getImageDescriptor("/icons/role_obj.gif")
					.createImage();
		}
		
		IRoleElement roleElement = (IRoleElement) adapterManager.getAdapter(
				element, IRoleElement.class);
		if (roleElement != null) {

			IEditorDescriptor editorDescriptor = BaseRoleElementAdapter
					.getDefaultEditor(roleElement);
			if (editorDescriptor != null
					&& editorDescriptor.getImageDescriptor() != null) {
				return editorDescriptor.getImageDescriptor().createImage();
			}
			return null;
		}

		return null;
	}

	public String getText(Object element) {

		if (element instanceof RoleRootElement) {
			return ((RoleRootElement) element).getName();
		}

		IRoleElement roleElement = (IRoleElement) adapterManager.getAdapter(
				element, IRoleElement.class);
		if (roleElement != null) {
			return roleElement.getName();
		}

		return null;
	}

	public IEditorRegistry getEditorRegistry() {
		return editorRegistry;
	}

	public void setEditorRegistry(IEditorRegistry editorRegistry) {
		this.editorRegistry = editorRegistry;
	}

	public IAdapterManager getAdapterManager() {
		return adapterManager;
	}

	public void setAdapterManager(IAdapterManager adapterManager) {
		this.adapterManager = adapterManager;
	}
}
